package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/convee/goblog/conf"
)

type IpInfo struct {
	Ip       string `json:"ip,omitempty"`
	Country  string `json:"country,omitempty"`
	Province string `json:"province,omitempty"`
	City     string `json:"city,omitempty"`
	Address  string `json:"address,omitempty"`
}

func Ip2Region(ip string) (IpInfo, error) {
	var client = &http.Client{}
	ipUrl := conf.Conf.App.IP2RegionUrl
	var url = fmt.Sprintf(ipUrl, ip)
	req, _ := http.NewRequest("GET", url, nil)
	var ipInfo IpInfo = IpInfo{
		City:     "Unknown",
		Province: "Unknown",
		Country:  "Unknown",
		Ip:       ip,
	}
	req.Header.Add("Yming-Auth", "Yming")
	resp, err := client.Do(req)

	if err != nil {
		return ipInfo, err
	}
	if resp.StatusCode != 200 {
		return ipInfo, nil
	}
	defer resp.Body.Close()
	//读取内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed, err:", err)
		return ipInfo, err
	}
	fmt.Println(string(body))

	if err = json.Unmarshal(body, &ipInfo); err != nil {
		fmt.Printf("Unmarshal err, %v\n", err)
		return ipInfo, err
	}
	return ipInfo, err
}
